const mysql = require('mysql2');

// 检查是否使用内存模式
const useMemoryStorage = process.env.DB_MODE === 'memory';

// 内存存储模拟
const memoryStorage = {
  users: [],
  functions: [],
  instances: []
};

if (useMemoryStorage) {
  console.log('使用内存存储模式');
  // 导出内存存储操作方法
  module.exports = {
    useMemoryStorage,
    memoryStorage,
    execute: memoryExecute,
    end: () => Promise.resolve()
  };
} else {
  console.log('使用MySQL数据库存储模式');
  // 创建数据库连接池
  const pool = mysql.createPool({
    host: process.env.DB_HOST || 'localhost',
    user: process.env.DB_USER || 'root',
    password: process.env.DB_PASSWORD || 'password',
    database: process.env.DB_NAME || 'function_manager',
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
  });

  // 导出连接池
  module.exports = {
    useMemoryStorage,
    memoryStorage,
    ...pool.promise()
  };
}

// 内存存储查询模拟函数
function memoryExecute(query, params = []) {
  query = query.trim();
  
  // 解析查询类型
  if (query.toUpperCase().startsWith('SELECT')) {
    return memorySelect(query, params);
  } else if (query.toUpperCase().startsWith('INSERT')) {
    return memoryInsert(query, params);
  } else if (query.toUpperCase().startsWith('UPDATE')) {
    return memoryUpdate(query, params);
  } else if (query.toUpperCase().startsWith('DELETE')) {
    return memoryDelete(query, params);
  } else if (query.toUpperCase().startsWith('CREATE')) {
    // CREATE TABLE 语句，直接返回
    return [{ affectedRows: 0 }, undefined];
  }
  
  // 默认返回
  return [ [], undefined ];
}

// 内存SELECT操作模拟
function memorySelect(query, params) {
  // 简化的表名提取
  let tableName = '';
  if (query.includes('FROM users')) {
    tableName = 'users';
  } else if (query.includes('FROM functions')) {
    tableName = 'functions';
  } else if (query.includes('FROM instances')) {
    tableName = 'instances';
  }
  
  let results = [...memoryStorage[tableName]];
  
  // 处理JOIN查询 (针对instances表)
  if (query.includes('JOIN')) {
    if (tableName === 'instances') {
      results = results.map(instance => {
        const func = memoryStorage.functions.find(f => f.id === instance.function_id);
        return {
          ...instance,
          function_name: func ? func.name : null
        };
      });
    }
  }
  
  // 处理WHERE条件 (简化版)
  if (params.length > 0 && query.includes('WHERE')) {
    const param = params[0]; // 简化处理，只考虑第一个参数
    if (tableName === 'users') {
      results = results.filter(item => item.username === param || item.id === param);
    } else {
      results = results.filter(item => item.id === param);
    }
  }
  
  // 处理ORDER BY
  if (query.includes('ORDER BY') && tableName === 'functions') {
    results.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
  } else if (query.includes('ORDER BY') && tableName === 'instances') {
    results.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
  }
  
  return [ results, undefined ];
}

// 内存INSERT操作模拟
function memoryInsert(query, params) {
  // 简化的表名提取
  let tableName = '';
  if (query.includes('INTO users')) {
    tableName = 'users';
    const [id, username, password] = params;
    memoryStorage[tableName].push({ 
      id, 
      username, 
      password,
      created_at: new Date().toISOString()
    });
  } else if (query.includes('INTO functions')) {
    tableName = 'functions';
    const [id, name, version, description, timeout, handler, image, env, limits, requests, code] = params;
    memoryStorage[tableName].push({ 
      id, 
      name, 
      version, 
      description, 
      timeout, 
      handler, 
      image, 
      env, 
      limits, 
      requests, 
      code,
      published: true, // 默认设为true
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString()
    });
  } else if (query.includes('INTO instances')) {
    tableName = 'instances';
    const [id, function_id, status, url] = params;
    memoryStorage[tableName].push({ 
      id, 
      function_id, 
      status, 
      url,
      created_at: new Date().toISOString()
    });
  }
  
  return [{ affectedRows: 1, insertId: params[0] }, undefined];
}

// 内存UPDATE操作模拟
function memoryUpdate(query, params) {
  // 简化的表名提取
  let tableName = '';
  let whereParam = params[params.length - 1]; // WHERE条件的参数通常是最后一个
  
  if (query.includes('UPDATE users')) {
    tableName = 'users';
  } else if (query.includes('UPDATE functions')) {
    tableName = 'functions';
  } else if (query.includes('UPDATE instances')) {
    tableName = 'instances';
  }
  
  // 找到要更新的记录
  const index = memoryStorage[tableName].findIndex(item => item.id === whereParam);
  
  if (index !== -1) {
    // 解析SET子句中的字段
    const setClause = query.substring(query.indexOf('SET') + 4, query.indexOf('WHERE')).trim();
    const fields = setClause.split(',').map(field => field.trim());
    
    // 更新字段
    fields.forEach(field => {
      const [fieldName, fieldValue] = field.split('=').map(part => part.trim());
      // 移除可能的引号和参数占位符
      const cleanFieldName = fieldName.replace(/`/g, '');
      if (fieldValue === '?') {
        // 从params中获取对应的值（除了最后一个WHERE参数）
        const paramIndex = fields.indexOf(field);
        memoryStorage[tableName][index][cleanFieldName] = params[paramIndex];
      } else {
        memoryStorage[tableName][index][cleanFieldName] = fieldValue.replace(/['"]/g, '');
      }
    });
    
    // 更新时间戳（如果存在）
    if (tableName === 'functions') {
      memoryStorage[tableName][index].updated_at = new Date().toISOString();
    }
    
    return [{ affectedRows: 1 }, undefined];
  }
  
  return [{ affectedRows: 0 }, undefined];
}

// 内存DELETE操作模拟
function memoryDelete(query, params) {
  // 简化的表名提取
  let tableName = '';
  if (query.includes('FROM users')) {
    tableName = 'users';
  } else if (query.includes('FROM functions')) {
    tableName = 'functions';
  } else if (query.includes('FROM instances')) {
    tableName = 'instances';
  }
  
  const param = params[0]; // WHERE条件的参数
  const initialLength = memoryStorage[tableName].length;
  
  // 过滤掉匹配的记录
  memoryStorage[tableName] = memoryStorage[tableName].filter(item => item.id !== param);
  
  const deletedRows = initialLength - memoryStorage[tableName].length;
  
  return [{ affectedRows: deletedRows }, undefined];
}